local tracer = require("skywalking.tracer")

--- 简易的nsq客户端,不同项目写法不同
--- 主要是在调用location.capture前，新建exit_span
local send_insq = function(topic, args, body_str, header_tb, delay)
    if topic == "" or nil == topic then
        return nil
    end
    local request_info = {
        args = args or "",
        body = body_str or "",
        headers = header_tb
    }

    local method = ngx.HTTP_GET
    if body_str then
        method = ngx.HTTP_POST
    end
    local uri = "/insq2_queue/insq/pub"
    -- 因为不同的分区，需要根据分区修改topic
    local new_topic = topic
    local should_topic = {
        ["topic1"] = 1,
    }
   
    local args = {
        topic = new_topic,
    }
    if delay then
        uri = "/insq2_queue/insq/delay_pub"
        args["delay"] = delay
    end

    ----------------------- **新增skywalking对nsq的链路追踪逻辑** ---------------------
    local injector = function(header, value)
        -- ned do add the header to the nsq,you can adjust the request_info
        request_info.headers =  request_info.headers or {}
        request_info.headers[header] = value
    end

    local exit_span = tracer:createExitSpan(ngx.ctx, tostring(topic), "nsq", injector)
    exit_span:setComponentId(exit_span.ComponentId_Constants.NsqClientComponentId)
    exit_span:setLayer(exit_span.SpanLayer.MQ)
    exit_span:tag(exit_span.Tag_Constants.TagMQTopic, tostring(topic))
    exit_span:tag(exit_span.Tag_Constants.TagHTTPParams, tostring(request_info.args))
    exit_span:tag(exit_span.Tag_Constants.TagHTTPBody, tostring(request_info.body_str))
    -----------------------------------------------------------------------------------
    
    local res = ngx.location.capture(uri,
    {
        args = args,
        method = method,
        body = cjson_safe.encode(request_info)
    })

    exit_span:tag(exit_span.Tag_Constants.TagHTTPStatus, tostring(res.status))
    
    ----------------------- **新增skywalking对nsq的链路追踪逻辑** ---------------------
    if res.status ~= 200 then
       
        exit_span:finish(ngx.now() * 1000)
        exit_span:error(ngx.now() * 1000, { key = "body:",  value = cjson_safe.encode(request_info) })
        return -1
    end

    exit_span:finish(ngx.now() * 1000)
    -----------------------------------------------------------------------------------
    return 0
end